<template>
  <div class="app2">
    <div class="hander">
      <h1 class="text">iHRM后台登录系统</h1>
      <el-form
        class="demo-ruleForm"
        ref="formRef"
        :model="params"
        :rules="rules"
      >
        <el-form-item prop="mobile">
          <el-input
            v-model="params.mobile"
            prefix-icon="el-icon-user-solid"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            show-password
            v-model="params.password"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="login"
            size="medium"
            @click="onLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as api from '../../api/login';

export default {
  data() {

    function checkMobile (rule, value, callback) {
      const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      if (!reg.test(value)) {
        callback(new Error('hello'));
      } else {
        callback();
      }
    }

    function checkPassword (rule, value, callback) {
      const reg = /^[a-zA-Z]|[0-9]|_$/;
      if (!reg.test(value)) {
        callback(new Error('hello'));
      } else {
        callback();
      }
    }

    // 密码：数字字母下划线
    return {
      params: {
        mobile: '13800000002',
        password: '123456',
      },
      rules: {
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ],
        password: [
          { validator: checkPassword, trigger: 'blur' }
        ],
      },
    };
  },
  methods: {
    onLogin () {
      this.$refs.formRef.validate(async (isPass) => {
        if (isPass) {
          const res = await api.login(this.params);
          if (res.data.success) {
            const token = res.data.data;
            localStorage.setItem('TOKEN', `Bearer ${ token }`);
            this.$message({
              message: res.data.message,
              type: 'success',
            });
            this.$router.push('/');
          } else {
            this.$message({
              message: res.data.message,
              type: 'error',
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.app2 {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-flow: column;
  align-items: center;
  justify-content: center;
  background: url('../../assets/images/login.jpg') no-repeat;
}
.hander {
  width: 400px;
  text-align: center;

  h1 {
      color: white;
  }
}
.login {
  width: 300px;
}
</style>
